<template>
  <div class="avue-top">
    <div class="top-bar__left">
      <div class="avue-breadcrumb" :class="[{ 'avue-breadcrumb--active': isCollapse }]" v-if="showCollapse">
        <i class="icon-navicon" style="color: #fff" @click="setCollapse"></i>
      </div>
    </div>
    <div class="top-bar__title">
      <div class="top-bar__item top-bar__item--show" v-if="showMenu">
        <top-menu ref="topMenu"></top-menu>
      </div>
      <span class="top-bar__item" v-if="showSearch">
        <top-search></top-search>
      </span>
    </div>
    <div class="top-bar__right">
      <!-- <el-tooltip
        v-if="showColor"
        effect="dark"
        :content="$t('navbar.color')"
        placement="bottom"
      >
        <div class="top-bar__item">
          <top-color></top-color>
        </div>
      </el-tooltip> -->

      <!-- <el-tooltip v-if="showTheme"
                  effect="dark"
                  :content="$t('navbar.theme')"
                  placement="bottom">
        <div class="top-bar__item top-bar__item--show">
          <top-theme></top-theme>
        </div>
      </el-tooltip> -->
      <!-- <el-tooltip v-if="showFullScren"
                  effect="dark"
                  :content="isFullScren?$t('navbar.screenfullF'):$t('navbar.screenfull')"
                  placement="bottom">
        <div class="top-bar__item">
          <i :class="isFullScren?'icon-tuichuquanping':'icon-quanping'"
             @click="handleScreen"></i>
        </div>
      </el-tooltip> -->
      <div style="display: flex; align-items: center">
        <img class="top-bar__img" style="width: 25px; height: 25px; padding: 0; border: 0"
          :src="bUserInfo.avatar || userInfo.avatar" />
        <span style="font-size: 14px; color: #666;">{{
          bUserInfo.username
        }}</span>

        <span style="
            cursor: pointer;
            font-size: 14px;
            color: #666;
            margin-left: 20px;
          " @click="showPasswordDialog">密码修改</span>

        <span style="
            cursor: pointer;
            font-size: 14px;
            color: #666;
            margin-left: 20px;
          " @click="logout">{{ $t("navbar.logOut") }}</span>
      </div>

      <!-- <el-dropdown>
        <span class="el-dropdown-link">
          {{ userInfo.userName }}
          <i class="el-icon-arrow-down el-icon--right" style="color: #fff"></i>
        </span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item>
            <router-link to="/">{{ $t("navbar.dashboard") }}</router-link>
          </el-dropdown-item>
          <el-dropdown-item>
            <router-link to="/info/index">{{
              $t("navbar.userinfo")
            }}</router-link>
          </el-dropdown-item>

          <el-dropdown-item @click.native="logout" divided
            >{{ $t("navbar.logOut") }}
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown> -->
      <el-dialog title="用户信息选择" append-to-body :visible.sync="userBox" width="350px">
        <avue-form ref="form" :option="userOption" v-model="userForm" @submit="submitSwitch" />
      </el-dialog>

      <!-- 密码修改对话框 -->
      <el-dialog title="密码修改" append-to-body :visible.sync="passwordDialog" width="500px">
        <el-form ref="passwordForm" :model="passwordForm" :rules="passwordRules" label-width="100px">
          <el-form-item label="原密码" prop="old_password">
            <el-input v-model="passwordForm.old_password" type="password" placeholder="请输入原密码" show-password></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="new_password">
            <el-input v-model="passwordForm.new_password" type="password" placeholder="请输入新密码" show-password></el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="confirm_password">
            <el-input v-model="passwordForm.confirm_password" type="password" placeholder="请确认新密码"
              show-password></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelPassword">取消</el-button>
          <el-button type="primary" @click="submitPassword">确认</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { resetRouter } from "@/router/router";
import { mapGetters, mapState } from "vuex";
import { fullscreenToggel, listenfullscreen } from "@/util/util";
import { removeToken } from "@/util/auth";
import { changePassword } from "@/api/user";
import topLock from "./top-lock";
import topMenu from "./top-menu";
import topSearch from "./top-search";
import topTheme from "./top-theme";
import topLogs from "./top-logs";
import topColor from "./top-color";
import topNotice from "./top-notice";
import topLang from "./top-lang";
import website from "@/config/website";

export default {
  components: {
    topLock,
    topMenu,
    topSearch,
    topTheme,
    topLogs,
    topColor,
    topNotice,
    topLang,
  },
  name: "top",
  data () {
    return {
      userBox: false,
      passwordDialog: false,
      bUserInfo: {},
      userForm: {
        deptId: "",
        roleId: "",
      },
      passwordForm: {
        old_password: "",
        new_password: "",
        confirm_password: "",
      },
      useroption: {
        menuType: 'button',
        labelWidth: 70,
        submitBtn: true,
        emptyBtn: false,
        submitText: "切换",
        column: [
          {
            label: "部门",
            prop: "deptId",
            type: "select",
            props: {
              label: "deptName",
              value: "id",
            },
            dicUrl: "/api/blade-system/dept/select",
            span: 24,
            display: false,
            rules: [
              {
                required: true,
                message: "请选择部门",
                trigger: "blur",
              },
            ],
          },
          {
            label: "角色",
            prop: "roleId",
            type: "select",
            props: {
              label: "roleName",
              value: "id",
            },
            dicUrl: "/api/blade-system/role/select",
            span: 24,
            display: false,
            rules: [
              {
                required: true,
                message: "请选择角色",
                trigger: "blur",
              },
            ],
          },
        ],
      },
      passwordRules: {
        old_password: [
          {
            required: true,
            message: "请输入原密码",
            trigger: "blur",
          },
        ],
        new_password: [
          {
            required: true,
            message: "请输入新密码",
            trigger: "blur",
          },
          {
            min: 6,
            message: "密码长度不能少于6位",
            trigger: "blur",
          },
        ],
        confirm_password: [
          {
            required: true,
            message: "请确认新密码",
            trigger: "blur",
          },
          {
            validator: (rule, value, callback) => {
              if (value !== this.passwordForm.new_password) {
                callback(new Error("两次输入的密码不一致"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
    };
  },
  filters: {},
  created () {
    const user = localStorage.getItem(website.key + "-user");
    if (user) this.bUserInfo = JSON.parse(user);
  },
  mounted () {
    listenfullscreen(this.setScreen);
  },
  watch: {
    passwordDialog (newVal) {
      if (newVal) {
        // 当对话框打开时，重置表单
        this.$nextTick(() => {
          this.$refs.passwordForm.clearValidate();
        });
      }
    }
  },
  computed: {
    ...mapState({
      showDebug: (state) => state.common.showDebug,
      showTheme: (state) => state.common.showTheme,
      showLock: (state) => state.common.showLock,
      showFullScren: (state) => state.common.showFullScren,
      showCollapse: (state) => state.common.showCollapse,
      showSearch: (state) => state.common.showSearch,
      showMenu: (state) => state.common.showMenu,
      showColor: (state) => state.common.showColor,
    }),
    ...mapGetters([
      "userInfo",
      "isFullScren",
      "tagWel",
      "tagList",
      "isCollapse",
      "tag",
      "logsLen",
      "logsFlag",
    ]),
  },
  methods: {
    handleScreen () {
      fullscreenToggel();
    },
    setCollapse () {
      this.$store.commit("SET_COLLAPSE");
    },
    setScreen () {
      this.$store.commit("SET_FULLSCREN");
    },
    switchDept () {
      const userId = this.userInfo.user_id;
      const deptColumn = this.findObject(this.userOption.column, "deptId");
      deptColumn.dicUrl = `/api/blade-system/dept/select?userId=${userId}`;
      deptColumn.display = true;
      const roleColumn = this.findObject(this.userOption.column, "roleId");
      roleColumn.dicUrl = `/api/blade-system/role/select?userId=${userId}`;
      roleColumn.display = true;
      this.userBox = true;
    },
    submitSwitch (form, done) {
      this.$store.dispatch("refreshToken", form).then(() => {
        this.userBox = false;
        this.$router.push({ path: "/" });
      });
      done();
    },
    showPasswordDialog () {
      this.passwordDialog = true;
      this.passwordForm = {
        old_password: "",
        new_password: "",
        confirm_password: "",
      };
    },
    submitPassword () {
      this.$refs.passwordForm.validate((valid) => {
        if (valid) {
          changePassword(this.passwordForm).then((res) => {
            console.log(res);
            if (res.err === 0) {
              this.$message.success("密码修改成功");
              this.passwordDialog = false;
            } else {
              this.$message.error(res.data.msg || "密码修改失败");
            }
          }).catch((error) => {
            this.$message.error("密码修改失败，请重试");
          });
        } else {
          return false;
        }
      });
    },
    cancelPassword () {
      // 清除表单验证状态
      this.$refs.passwordForm.clearValidate();
      // 重置表单数据
      this.passwordForm = {
        old_password: "",
        new_password: "",
        confirm_password: "",
      };
      // 关闭对话框
      this.passwordDialog = false;
    },
    logout () {
      this.$confirm(this.$t("logoutTip"), this.$t("tip"), {
        confirmButtonText: this.$t("submitText"),
        cancelButtonText: this.$t("cancelText"),
        type: "warning",
      }).then(() => {
        removeToken();
        localStorage.removeItem(website.key + "-token");
        localStorage.removeItem(website.key + "-user");
        localStorage.removeItem(website.key + "-routes");
        location.reload();
        resetRouter();
      });
    },
  },
};
</script>

<style lang="scss" scoped></style>
